// 路由模块

import { createRouter, createWebHistory } from "vue-router";
import { ElMessage } from "element-plus";

import Login from "../views/Login/index.vue";
import { getMenusApi } from "@/api/menusApi";
import dealWithRoute from "./dealWithRoute.js";
const routes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    name: "login",
    path: "/login",
    component: Login,
    meta: {
      title: "管理员登录",
    },
  },
  {
    name: "reg",
    path: "/reg",
    component: () => import("../views/Reg/index.vue"),
    meta: {
      title: "新用户注册",
    },
  },
  {
    name: "main",
    path: "/main",
    component: () => import("../views/Main/index.vue"),
    redirect: "/main/home",
    children: [
      {
        name: "首页",
        path: "home",
        component: () => import("@/views/Home/index.vue"),
      },
    ],
  },
  {
    name: "404",
    path: "/:pathMatch(.*)*",
    component: () => import("../views/404.vue"),
    meta: {
      title: "404",
    },
  },
];
let menuList = [];
const router = createRouter({
  routes,
  history: createWebHistory(),
});
let hasRoles = false;
// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 登录和注册页面，不需要拦截

  menuList = JSON.parse(sessionStorage.getItem("menuList"));

  if (to.path === "/login" || to.path === "/reg") {
    next();
  } else {
    if (!hasRoles) {
      getMenu();
      hasRoles = true;

      next({ ...to, replace: true });
    } else {
      next();
    }
  }

  // if (!menuList) {
  //   getMenu();
  // }

  // 其它页面验证用户是否登录
  // const token = sessionStorage.getItem("token");
  // if (!token) {
  //   ElMessage({
  //     type: "error",
  //     message: "用户尚未登录，请登录后访问",
  //   });
  //   // 跳转到登录页面
  //   next({ name: "login" });
  // } else {
  //   next();
  // }
});

const getMenu = async () => {
  const res = await getMenusApi();
  sessionStorage.setItem("menuList", JSON.stringify(res.msg));
  console.log(56);
  dealWithRoute(res.msg);
};

export default router;
